> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/jaypopat/cf_ai_duet/llms.txt
> Use this file to discover all available pages before exploring further.

# Terminal Package

> PTY-based terminal emulation with multi-client support

## Overview

The `terminal` package provides a shared terminal session using PTY (pseudo-terminal) with VT10x emulation. Multiple clients can connect to the same terminal and see synchronized output.

## Type

### Terminal

Wraps a PTY with VT10x terminal emulation and subscriber management.

```go theme={null}
type Terminal struct {
    vt   vt10x.Terminal
    ptmx *os.File
    cmd  *exec.Cmd
    mu   sync.Mutex
    
    width   int
    height  int
    workDir string
    
    subscribers map[chan struct{}]struct{}
    subMu       sync.RWMutex
    closed      bool
    
    lastRender string
    dirty      bool
}
```

## Functions

### New

Creates a new terminal instance.

```go theme={null}
func New(width, height int, workDir string) *Terminal
```

<ParamField path="width" type="int" required>
  Terminal width in columns (defaults to 80 if \< 1)
</ParamField>

<ParamField path="height" type="int" required>
  Terminal height in rows (defaults to 24 if \< 1)
</ParamField>

<ParamField path="workDir" type="string" required>
  Working directory for shell (defaults to "/app" if empty)
</ParamField>

**Example:**

```go theme={null}
term := terminal.New(120, 30, "/app/workspaces/my-project")
```

### Start

Starts the shell process and begins reading output.

```go theme={null}
func (t *Terminal) Start() error
```

**Returns:** Error if PTY creation or shell start fails

**Behavior:**

* Creates VT10x terminal emulator
* Spawns shell process (respects `$SHELL` env var, defaults to `/bin/sh`)
* Sets environment: `TERM=xterm-256color`
* Starts background read loop

**Example:**

```go theme={null}
term := terminal.New(80, 24, "/app")
if err := term.Start(); err != nil {
    log.Fatal(err)
}
```

### Write

Sends input to the terminal (keyboard input, etc.).

```go theme={null}
func (t *Terminal) Write(data []byte) (int, error)
```

<ParamField path="data" type="[]byte" required>
  Raw input data to send to PTY
</ParamField>

**Returns:** Bytes written and error

**Example:**

```go theme={null}
// Send "ls" command
term.Write([]byte("ls\r"))

// Send Ctrl+C
term.Write([]byte{0x03})
```

### Render

Renders the current terminal state to a string with ANSI codes.

```go theme={null}
func (t *Terminal) Render() string
```

**Returns:** Rendered terminal output with colors and formatting

**Features:**

* Caching: Returns cached render if terminal hasn't changed
* Colors: Full 256-color ANSI support
* Cursor: Visual cursor using reverse video effect
* Optimization: Run-length encoding for color sequences

**Example:**

```go theme={null}
output := term.Render()
fmt.Print(output)
```

### Resize

Resizes the terminal dimensions.

```go theme={null}
func (t *Terminal) Resize(width, height int)
```

<ParamField path="width" type="int" required>
  New width in columns
</ParamField>

<ParamField path="height" type="int" required>
  New height in rows
</ParamField>

**Behavior:**

* Updates VT10x emulator size
* Sends `SIGWINCH` via `pty.Setsize()`
* Invalidates render cache

### Close

Closes the terminal and cleans up resources.

```go theme={null}
func (t *Terminal) Close() error
```

**Cleanup:**

* Closes all subscriber channels
* Closes PTY file descriptor
* Kills shell process

### Size

Returns current terminal dimensions.

```go theme={null}
func (t *Terminal) Size() (width, height int)
```

## Subscription Pattern

The terminal supports multi-client subscriptions for real-time updates.

### Subscribe

Creates a channel for receiving update notifications.

```go theme={null}
func (t *Terminal) Subscribe() chan struct{}
```

**Returns:** Channel that receives a signal on each terminal update

**Example:**

```go theme={null}
updates := term.Subscribe()
defer term.Unsubscribe(updates)

for range updates {
    output := term.Render()
    updateUI(output)
}
```

### Unsubscribe

Removes a subscription channel.

```go theme={null}
func (t *Terminal) Unsubscribe(ch chan struct{})
```

<ParamField path="ch" type="chan struct{}" required>
  Channel returned by Subscribe()
</ParamField>

## Implementation Details

### Read Loop

The background `readLoop()` goroutine:

1. Reads from PTY (4KB buffer)
2. Writes to VT10x emulator
3. Marks terminal as dirty
4. Broadcasts to all subscribers
5. Exits when shell process terminates

### Render Optimization

```go theme={null}
// Return cached render if not dirty
if !t.dirty && t.lastRender != "" {
    return t.lastRender
}
```

The terminal caches renders and only re-renders when content changes, reducing CPU usage for idle terminals.

### Color Mapping

```go theme={null}
func fgColor(c vt10x.Color) string
func bgColor(c vt10x.Color) string
```

Maps VT10x colors to ANSI escape codes:

* Colors 0-7: Standard ANSI (30-37, 40-47)
* Colors 8-15: Bright ANSI (90-97, 100-107)
* Colors 16-255: Extended palette (38;5;n, 48;5;n)

## Thread Safety

All public methods are thread-safe:

* `mu sync.Mutex` protects terminal state
* `subMu sync.RWMutex` protects subscriber map
